package com.md.iotest;


import java.io.*;

/**
 * @Author Gong
 * @Description
 * @dATE 2022/3/28 15:43
 **/
public class ReaderWriterTest {
    static String path = "d:/temp/io/";
    public static void main(String[] args) throws IOException {
        ReaderWriterTest rwt = new ReaderWriterTest();
        rwt.replaceFile();
    }
    public void replaceFile() throws IOException {
        Reader fr =   new FileReader("d:/temp/io/"+ File.separator+"1.txt");
        int l = -1;
        char[] buf = new char[1024];
        BufferedReader br = new BufferedReader(fr);
        StringBuffer sb = new StringBuffer();
        while((l = br.read(buf)) > -1){
            sb.append(buf,0,buf.length);
        }

        //替换字符串指定的内容
        String res = sb.toString().replace("{name}","小白")
                .replace("{type}","吉娃娃")
                .replace("{master}","张三");

        //回写文件
        Writer fw =   new FileWriter("d:/temp/io/"+ File.separator+"2.txt");
        BufferedWriter bw = new BufferedWriter(fw);
        //
        bw.write(res);
        bw.flush();//立刻把缓冲数据刷到磁盘
        bw.close();
        fw.close();
    }
    /**
     * @Author GongXL
     * @Description  复制字符文件
     * @Date 16:28 2022/3/28
     * @Param []
     * @return void
     **/
    public void copyFile() throws IOException {
        Reader fr =   new FileReader("d:/temp/io/"+ File.separator+"1.txt");
        Writer fw =   new FileWriter("d:/temp/io/"+ File.separator+"writer.txt");
        int l = -1;
        char[] buf = new char[1024];
        BufferedReader br = new BufferedReader(fr);
        BufferedWriter bw = new BufferedWriter(fw);
        while((l = br.read(buf)) > -1){
            bw.write(buf,0,buf.length);
        }
        bw.flush();//立刻把缓冲数据刷到磁盘
        bw.close();
        fw.close();
    }
    public  void writeFile() throws IOException {
        Writer fr =   new FileWriter("d:/temp/io/"+ File.separator+"writer.txt");
        BufferedWriter bw = new BufferedWriter(fr);
        bw.write("我热爱中国#");
        bw.flush();
        bw.close();
    }
    public  void readFile() throws IOException {
        Reader fr =   new FileReader("d:/temp/io/"+ File.separator+"1.txt");
        int l = -1;
        char[] buf = new char[1024];
        BufferedReader br = new BufferedReader(fr);
        StringBuffer sb = new StringBuffer();
        while((l = br.read(buf)) > -1){
            sb.append(buf,0,buf.length);
        }
        fr.close();
        System.out.println(sb.toString());
    }
}
